package com.imooc.controller;

import com.imooc.pojo.Users;
import com.imooc.pojo.bo.UserBO;
import com.imooc.pojo.bo.UserLoginBO;
import com.imooc.service.UserService;
import imooc.utils.CookieUtils;
import imooc.utils.ApiResponse;
import imooc.utils.JsonUtils;
import imooc.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Api(value = "用户注册接口部分", tags = {"用户注册"})
@RestController
@RequestMapping("/passport")
public class PassportController {

    @Autowired
    private UserService userService;

    /**
     * 判断用户名是否存在
     * */
    @GetMapping("/usernameIsExist")
    @ApiOperation(value = "判断用户名是否存在", notes = "判断用户名是否存在", httpMethod = "GET")
    public ApiResponse usernameIsExist(@RequestParam String username) throws Exception{
        if (StringUtils.isBlank(username)) {
            return ApiResponse.errorMsg("用户名不能为空");
        }
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist) {
            return ApiResponse.errorMsg("用户名已经存在");
        }
        return ApiResponse.ok();
    }

    /**
     * @author cg.hu
     * @version 2.6
     * @date 2021/1/12 14:16
     * @description   用户注册
     **/
    @PostMapping("/regist")
    @ApiOperation(value = "用户注册", notes = "用户注册", httpMethod = "POST")
    public ApiResponse regist(@RequestBody UserBO userBO, HttpServletRequest request,
                              HttpServletResponse response) throws Exception{

        if (!userBO.isTrue(userBO.getPassword(), userBO.getConfirmPassword())) {
            return ApiResponse.errorMsg("密码和确认密码必须一致");
        }
        // 校验 密码长度
        int len = userBO.getPassword().length();
        if (len < 6 || len > 20) {
            return ApiResponse.errorMsg("密码长度必须在6-20之间");
        }
        // 判断用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(userBO.getUsername());
        if (isExist) {
            return ApiResponse.errorMsg("用户名已经存在");
        }
        //
        Users users = userService.createUser(userBO);

        users = setNullProperty(users);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(users), true);

        if (null == users) {
            return ApiResponse.errorMsg("添加用户失败");
        }

        // TODO 生成用户TOKEN, 存入 redis会话
        // TODO 同步购物车数据

        return ApiResponse.ok(users);
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "登录", httpMethod = "POST")
    public ApiResponse login(@RequestBody @Valid UserLoginBO userBO, HttpServletRequest request,
                             HttpServletResponse response) throws Exception{
        String username = userBO.getUsername();
        String password = userBO.getPassword();

        // 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ApiResponse.errorMsg("用户名或密码不能为空");
        }

        Users users = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));
        if (null == users) {
            return ApiResponse.errorMsg("用户不存在，登录失败");
        }

        users = setNullProperty(users);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(users), true);

        // TODO 生成用户TOKEN, 存入 redis会话
        // TODO 同步购物车数据

        return ApiResponse.ok(users);
    }

    private Users setNullProperty(Users users) {
        users.setPassword(null);
        users.setMobile(null);
        users.setEmail(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
        users.setBirthday(null);
        return users;
    }

    /**
     * @author cg.hu
     * @version 2.6
     * @date 2021/1/15 16:26
     * @description    用户退出登录
     **/
    @PostMapping("/logout")
    @ApiOperation(value = "用户退出登录", notes = "用户退出登录", httpMethod = "POST")
    public ApiResponse logout(@RequestParam String userId,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        CookieUtils.deleteCookie(request, response, "user");

        // TODO 用户退出登录，需要清空购物车
        // TODO 分布式会话中需要清除用户数据

        return ApiResponse.ok();
    }
}
